package com.itheima.aop;

import com.itheima.interceptor.TokenInterceptor;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.CurrentHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
public class OperationLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Pointcut("@annotation(com.itheima.anno.Flag)")
    public void pt() {
    }

    @Around("pt()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
//        记录开始时间
        long startTime = System.currentTimeMillis();
//        执行方法
        Object result = pjp.proceed(pjp.getArgs());
//        结束时间
        long endTime = System.currentTimeMillis();
//        耗时
        long costTime = endTime - startTime;

        OperateLog operateLog = new OperateLog();
//        获取操作人id

        operateLog.setOperateEmpId(CurrentHolder.getCurrentId());
//        操作时间
        operateLog.setOperateTime(LocalDateTime.now());
//        操作类名
        operateLog.setClassName(pjp.getTarget().getClass().getName());
//        操作方法名
        operateLog.setMethodName(pjp.getSignature().getName());
//        操作方法参数
        operateLog.setMethodParams(Arrays.toString(pjp.getArgs()));
//        操作方法返回值
        operateLog.setReturnValue(result.toString());
//        操作耗时
        operateLog.setCostTime(costTime);

        operateLogMapper.insert(operateLog);
        return result;
    }

}
